<template>
  <div class="role">
    <el-button type="primary" :icon="useRenderIcon(plus)" @click="add"
      >新增</el-button
    >
    <div class="my-table mt-4">
      <el-table :data="tableData" style="width: 100%" v-loading="listLoading">
        <el-table-column prop="roleKey" label="角色key" />
        <el-table-column prop="name" label="角色名称" />
        <el-table-column label="操作" align="center">
          <template v-slot="scope">
            <el-tooltip
              class="box-item"
              effect="dark"
              content="分配菜单"
              placement="top"
            >
              <el-button
                type="primary"
                size="small"
                :icon="useRenderIcon(stamp)"
                @click="assignMenu(scope.row)"
              />
            </el-tooltip>
            <el-tooltip
              class="box-item"
              effect="dark"
              content="分配权限"
              placement="top"
            >
              <el-button
                type="primary"
                size="small"
                :icon="useRenderIcon(menu)"
                @click="assignPermission(scope.row)"
              />
            </el-tooltip>

            <el-button
              type="primary"
              size="small"
              :icon="useRenderIcon(edit)"
              @click="editItem(scope.row)"
            />
            <el-button
              type="primary"
              :icon="useRenderIcon(iconDel)"
              size="small"
              @click="del(scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>
      <div class="pagi flex flex-row-reverse mt-4">
        <el-pagination
          @current-change="currentChange"
          v-model:page-size="query.pageSize"
          :page-sizes="[10, 20, 30, 40]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        />
      </div>
    </div>
    <!-- 添加编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑角色' : '新增角色'"
      width="50%"
      @closed="closed"
    >
      <div class="dialog-content">
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="120px"
          class="demo-ruleForm"
          status-icon
        >
          <el-form-item label="角色Key" prop="roleKey">
            <el-input v-model="ruleForm.roleKey" />
          </el-form-item>
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="ruleForm.name" />
          </el-form-item>

          <div class="ml-[50px] mt-[40px]">
            <p>说明</p>
            <p>角色key 英文数字下划线</p>
            <p>角色key 只能r_开头</p>
          </div>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submit" :loading="isLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 分配菜单弹窗 -->
    <menuDialog
      :role-id="roleId"
      v-model="assignDialogVisible"
      @getList="getList"
    />
    <!-- 权限分配 -->
    <permissionDialog
      :role-id="roleId"
      v-model="permissionDialogVisible"
      @getList="getList"
    />
  </div>
</template>

<script setup lang="ts">
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import plus from "@iconify-icons/ep/plus";
import iconDel from "@iconify-icons/ep/delete";
import edit from "@iconify-icons/ep/edit";
import menu from "@iconify-icons/ep/menu";
import stamp from "@iconify-icons/ep/stamp";
import { reactive, ref } from "vue";
import { removeRole, getRoleList, addRole, editRole } from "@/api/system/index";
import {
  ElMessage,
  ElMessageBox,
  type FormInstance,
  type FormRules
} from "element-plus";
import type { RoleResponse, AddRoleParams } from "@/api/system/system";
import { watch } from "vue";
import menuDialog from "./components/menuDialog.vue";
import permissionDialog from "./components/permissionDialog.vue";
defineOptions({
  name: "role"
});
// 获取数据
const query = reactive({
  page: 0,
  pageSize: 10
});
const currentChange = (val: number) => {
  query.page = val - 1;
};
const tableData = ref<RoleResponse[]>([]);
const total = ref(0);
const listLoading = ref(false);
const getList = async () => {
  listLoading.value = true;
  const res = await getRoleList(query);
  if (res.code === 0) {
    total.value = res.data.total;
    tableData.value = res.data.pageData;
    listLoading.value = false;
  }
};
watch(
  query,
  () => {
    getList();
  },
  {
    deep: true,
    immediate: true
  }
);
const ruleForm = ref<AddRoleParams>({
  roleKey: "",
  name: ""
});
const rules = reactive<FormRules<AddRoleParams>>({
  roleKey: [{ required: true, message: "请输入权限字符串", trigger: "blur" }],
  name: [{ required: true, message: "请输入权限描述", trigger: "blur" }]
});
const ruleFormRef = ref<FormInstance>();
// 添加
const add = () => {
  isEdit.value = false;
  dialogVisible.value = true;
};
// 编辑
const roleId = ref("");
const editItem = (item: RoleResponse) => {
  for (const key in ruleForm.value) {
    ruleForm.value[key] = item[key];
  }
  roleId.value = item.roleId;
  isEdit.value = true;
  dialogVisible.value = true;
};
// 删除
const del = (item: RoleResponse) => {
  ElMessageBox.confirm("您确定要删除吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      const res = await removeRole(item.roleId);
      if (res.code === 0) {
        ElMessage({
          type: "success",
          message: "删除成功"
        });
        getList();
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消"
      });
    });
};
// 弹窗
const dialogVisible = ref(false);
const isEdit = ref(false);
const closed = () => {
  ruleForm.value = {
    name: "",
    roleKey: ""
  };
  ruleFormRef.value.clearValidate();
};
// 添加提交
const addSubmit = async () => {
  const res = await addRole(ruleForm.value);
  if (res.code === 0) {
    ElMessage.success("添加成功");
  }
};
// 编辑提交
const editSubmit = async () => {
  const form = { ...ruleForm.value, roleId: roleId.value };
  const res = await editRole(form);
  if (res.code === 0) {
    ElMessage.success("修改成功");
  }
};
// 提交
const isLoading = ref(false);
const submit = () => {
  ruleFormRef.value.validate(async valid => {
    if (valid) {
      isLoading.value = true;
      if (isEdit.value) {
        await editSubmit();
      } else {
        await addSubmit();
      }
      isLoading.value = false;
      dialogVisible.value = false;
      getList();
    }
  });
};
// 分配菜单
const assignDialogVisible = ref(false);
const assignMenu = (item: RoleResponse) => {
  roleId.value = item.roleId;
  assignDialogVisible.value = true;
};
// 分配权限
const permissionDialogVisible = ref(false);
const assignPermission = (item: RoleResponse) => {
  roleId.value = item.roleId;
  permissionDialogVisible.value = true;
};
</script>
